package day12.convertedstream;

import java.io.*;

/**
 * @author Xiao
 * @date 2021/8/2
 */
public class ObjectOperateStreamCase01 {
    /**
     *  对象操作流读写多个对象
     *      创建多个Javabean类对象写到文件中，再次读取到内存中。
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student stu1 = new Student("阿良", 24);
        Student stu2 = new Student("左右", 24);
        Student stu3 = new Student("平安", 24);
        Student stu4 = new Student("小扁担", 12);
        Student stu5 = new Student("大水怪", 15);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
                "videoPractice\\src\\day12\\otherstream\\convertedstream\\ooscase1.txt"));
        Student[] stuArr = {stu1, stu2, stu3, stu4, stu5};
        oos.writeObject(stuArr);
        oos.close();
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
                "videoPractice\\src\\day12\\otherstream\\convertedstream\\ooscase1.txt"));
        Student[] stus = (Student[]) ois.readObject();
        for (Student stu : stus) {
            System.out.println(stu);
        }
        ois.close();
//        method2(oos, stuArr);
    }

    private static void method2(ObjectOutputStream oos, Student[] stuArr) throws IOException, ClassNotFoundException {
        for (Student stu : stuArr) {
            oos.writeObject(stu);
        }
        oos.close();
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
                "videoPractice\\src\\day12\\otherstream\\convertedstream\\ooscase1.txt"));
//        method1(ois);
        while (true) {
            try {
                System.out.println(ois.readObject());
            } catch (EOFException e) {
                break;
            }
        }
        ois.close();
    }

    private static void method1(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        Student stu;
        //EOFException:表示在输入过程中意外地到达文件结束或流结束。
        while ((stu = (Student) ois.readObject()) != null) {
            System.out.println(stu);
        }
    }
}
